from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *

class cfAction(QAction):
    def __init__(self,name,iface):
        QAction.__init__(self,self.name(),iface.getMainWindow())
        self.iface=iface
        self.canvas=iface.getMapCanvas()
        self.setWhatsThis(self.desc())
        self.setToolTip(self.desc())
        QObject.connect(self,SIGNAL("activated()"),self.doit)
        return None

    def doit(self):
        self.tool=cfTool(self.iface,self.createURL)
        self.canvas.setMapTool(self.tool)
        return None

class cfTool(QgsMapTool):
    def __init__(self,iface,urlCreator):
        QgsMapTool.__init__(self,iface.getMapCanvas())
        self.iface=iface
        self.canvas=iface.getMapCanvas()
        self.urlCreator=urlCreator
        return None
    def canvasReleaseEvent(self,e):
        point = self.canvas.getCoordinateTransform().toMapPoint(e.pos().x(),e.pos().y())
        url = self.urlCreator(point.y(),point.x())
        QDesktopServices.openUrl(QUrl(url))
        return None

def convertLat(lat):
    """ convert latitude in signed decimal degrees to (degrees, minutes, seconds, hemisphere) """
    return convertDMS(lat,"NS")

def convertLon(lon):
    return convertDMS(lon,"EW")

def convertDMS(dms,hemis):
    if dms > 0:
        hemi=hemis[0]
    else:
        hemi=hemis[1]
        dms=-dms
    d = int(dms)
    ms = (dms-d) * 60.0
    m = int(ms)
    s = (ms - m) * 60.0
    return (d,m,s,hemi)
